const PDFDocument = require('pdfkit');
const fs = require('fs');
const sharp = require('sharp');
const { getImageFilesInFolder, convertWebpToPng, getImageData } = require('./utils/getImageFilesInFolder');


async function addImage(doc, imagePath, index) {
    try {
        const filePath = await convertWebpToPng(imagePath)//转换为pdfkit支持的png格式文件
        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            throw (`图片不存在: ${filePath}`)
        }
        // 读取图片为 buffer
        const imageBuffer = fs.readFileSync(filePath);
        console.log(imagePath, index)
        // 添加图片到 PDF
        doc.image(imageBuffer, 0, 0, {
            width: doc.page.width,
            height: doc.page.height,
            align: 'center',
            valign: 'center'
        });

        // 如果不是最后一张图片，添加新的页面
        if (index < imagePaths.length - 1) {
            doc.addPage();
        } else {
            //关闭文件流
            doc.end();
        }
        // 删除convertWebpToPng临时转换的文件
        if (imagePath !== filePath) {
            fs.unlinkSync(filePath);
        }
    } catch (error) {
        console.error(`Error adding image ${imagePath}:`, error);
    }
}
async function imagesToPdf(imagePaths, outputPath) {
    const margin = 50; // 定义边距
    const doc = new PDFDocument({
        size: 'A4', // 设置 PDF 页面大小为 A4
        autoFirstPage: false,
        margin
    });
    // 先添加第一页
    doc.addPage();
    const stream = fs.createWriteStream(outputPath);

    doc.pipe(stream);
    for (let i = 0; i < imagePaths.length; i++) {
        await addImage(doc, imagePaths[i], i)
    }
    stream.on('finish', () => {
        console.log(`成功创建PDF文件: ${outputPath}`);
    });

    stream.on('error', (error) => {
        console.error('Error writing PDF file:', error);
    });
}
const folderPath = './public'//指定图片文件夹目录
const outputPath = 'outpdf.pdf';//输出文件
const imagePaths = getImageFilesInFolder(folderPath);//指定图片文件夹目录所有文件
imagesToPdf(imagePaths, outputPath);